<template>
  <div>
    <div >
      <!--工具类-->

      <Row :class="['chat_msg_detail_parent',direction==='row'?'':'chat_row_reverse']" >
        <i-col v-if="this.$yMobile()" style="padding: 0.5rem;">
          <Button size="small" @click="switchMobileInfo()"> {{showBaseInfoMobile?"切回聊天窗口":"查看基本信息"}} </Button>
        </i-col>
        <i-col :xs="{ span: 24, offset: 0 }" :sm="{ span: 8, offset:0 }" v-show="!this.$yMobile()||(this.$yMobile()&&showBaseInfoMobile)"
               :class-name="this.$yMobile()?'chat_baseinfo_mobile':'chat_baseinfo'">
          <Collapse class="list_section" v-model="collapseValue" >
            <Panel name="1">
              基本信息
              <p slot="content">
                <span class="list_key">用户:</span><span class="list_value">{{messageUserInfo.userCode}}</span>
<!--                <span class="list_key" v-has=tRole.CHAT_2_205>用户全名:</span><span class="list_value" v-has=tRole.CHAT_2_205>{{messageUserInfo.userName}}</span>-->
                <span class="list_key">国家:</span><span class="list_value">{{messageUserInfo.country}}</span>
                <span class="list_key">系统:</span><span class="list_value">{{deviceTypeLabel}}</span>
                <span class="list_key">版本:</span><span class="list_value">{{messageUserInfo.version}}</span>
                <span class="list_key">注册时间:</span><span class="list_value">
                {{$tiyBJTime(messageUserInfo.registertime)}}
                </span>
                <span class="list_key">注册方式:</span><span class="list_value">{{registerTypeLabel}}</span>
                <span class="list_key">订单数量:</span><span class="list_value">{{messageUserInfo.orderCount}}</span>
                <span class="list_key">购物车项目数:</span><span class="list_value">{{messageUserInfo.cartCount}}</span>
                <span class="list_key">LiveChat邮箱:</span><span class="list_value" style="word-break: break-all;">{{isEmpty(tData.userEmail.email)?"无":tData.userEmail.email}}</span>
              </p>
              <p slot="content">
                <Select v-model="messageUserInfo.tabId"  style="width: 13rem;margin-top: 0.5rem;font-weight: normal;"
                        filterable multiple  placeholder="用户标签">
                  <Option v-for="item in tData.tabList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
                <Button type="primary" style="margin-left: 0.5rem;margin-top: 0.5rem;" @click="saveUserTab()" ghost size="small">保存</Button>
              </p>
            </Panel>
            <Panel name="2">
              关联查询
              <p slot="content">
                <Row style="display: flex;flex-direction: row;" >
                  <Button size="small" style="margin-top: 0.5rem;margin-right: 0.5rem" @click="showProductSearch()">查询产品</Button>
                  <Button size="small" style="margin-top: 0.5rem;margin-right: 0.5rem" @click="showUserOrders()">查询用户订单</Button>
                  <Button size="small" style="margin-top: 0.5rem;margin-right: 0.5rem" @click="showUserCart">用户购物车</Button>
                  <Button size="small" style="margin-top: 0.5rem;margin-right: 0.5rem" @click="showUserRecords">登录记录</Button>

                </Row>
              </p>
            </Panel>


          </Collapse>

          <div>
            <p class="list_section">标签管理</p>
            <Row justify="center" align="middle"  >
              <i-col span="24">
                <Select v-model="selectedTags" filterable multiple allow-create @on-create="">
                  <Option v-for="item in tagList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </i-col>
              <i-col span="24" style="text-align: right;margin: 0.25rem">
                <Button type="info" @click="saveStatusTags()" ghost size="small">保存</Button>
              </i-col>
            </Row>
          </div>

          <div style="margin-top: 1rem">
            <p class="list_section">备注管理  <Button icon="md-create" size="small" style="margin-left: 1rem" @click="showNoteModal()"></Button></p>
            <span class="base_value y_wordwrap" style="font-size: 12px;  white-space: pre-line;">
<!--              <pre style="margin: 0px; padding: 0px;">{{tData.messageStatus.note}}</pre>-->
              {{tData.messageStatus.note}}
            </span>
          </div>

          <div style="margin-top: 1rem">
            <p class="list_section">会话管理</p>
            <div>
              <span class="list_key">负责员工:</span><span class="list_value">{{tData.messageStatus.employeeId==undefined?"无":tData.messageStatus.employeeName}}</span>
              <span class="list_value" style="color:#2D8cF0;font-size: 13px;cursor: pointer" @click="showAssign(userId)" v-has=tRole.CHAT_2_203>
                {{tData.messageStatus.employeeId==undefined?'分配':'更改'}}
              </span>
            </div>
            <div style="margin-top: 0.5rem">
              <span class="list_key">会话状态:</span><span class="list_value">{{tData.messageStatus.state==undefined?'无':messageStatusLabel(tData.messageStatus.state)}}</span>
              <span class="list_value" style="color:#2D8cF0;font-size: 13px;cursor: pointer" @click="showStateModal(tData.messageStatus.userId, tData.messageStatus.state)"
                    >更改</span>
            </div>
          </div>

<!--          <div style="margin-top: 1rem;">
            <p class="list_section">用户邮箱管理<Button icon="md-create" size="small" style="margin-left: 1rem" @click="showEmailModal()"></Button></p>
            <div>
              <span class="list_key">邮箱</span>
              <span class="list_value">{{isEmpty(tData.userEmail.email)?"无":tData.userEmail.email}}</span>
            </div>
            <div>
              <span class="list_key">备注</span>
              <span class="list_value">{{isEmpty(tData.userEmail.note)?"无":tData.userEmail.note}}</span>
            </div>
          </div>-->
        </i-col>
        <i-col :xs="{ span: 24, offset: 0 }" :sm="{ span: 16, offset:0 }" style="min-height: 80vh" v-show="!this.$yMobile()||(this.$yMobile()&&!showBaseInfoMobile)">

          <!--自动刷新-->
          <div style="position: absolute; width: 100%; top: 0; left: -15px; text-align: center;z-index: 999;">
            <div style="display: flex; width: 200px; margin: 0 auto; padding-left: 10px;box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
            justify-content: center; align-items: center; background-color: #ffffff; height: 30px; line-height: 30px;">
              <span v-show="isLoading">刷新中...</span>
              <Checkbox v-model="refresh" v-show="!isLoading" style="align-items: center; color: #2d8cf0; margin-right: 0.2rem;">
                <span style="margin-left: 0.2rem;">{{refresh?refreshTime+'秒后将自动刷新':'选中自动更新消息'}}</span>
              </Checkbox>
              <Icon type="md-refresh-circle" :class="isLoading?'loading':''"
                    style="font-size: 18px; color: #81d4fa; cursor: pointer;"
                    title="立即刷新消息"  @click="search(false)"></Icon>
            </div>
          </div>

          <table style="width: 100%; height: 100%;">
            <tr style="margin: 0; padding: 0;">
              <td style="margin: 0; padding: 0;">
                <div class="chat_content" id="chat_content">
                  <!--loading-spin-->
                  <div class="chat_spin" v-show="preLoading">
                    <img  class="spin_loading Rotation" src="https://image.fashiontiy.com/imgs/spin_loading.svg"
                          style="transform: rotate(360deg);-webkit-transform: rotate(360deg);animation: rotation 2s linear infinite;-moz-animation: rotation  2s linear infinite;
                    -webkit-animation: rotation  2s linear infinite;
                    -o-animation: rotation  2s linear infinite;">
                  </div>
                  <div class="chat_prev" v-show="showLoadingPre &&!preLoading&&hasPre" @click="handleReachEdge">
                    <span><i class="icon ion-md-arrow-up" ></i>Previous Messages</span>
                  </div>
                  <div class="chat_end" v-show="!hasPre" >
                    <span><i class="icon ion-md-arrow-up" ></i>No More Item</span>
                  </div>
                  <div id="chat_body">
                    <div v-for="(item,index) in messageList" class="chat_base_content" >
                      <!--right msg-->
                      <div class="chat_base" v-if="item.direction===2" >
                        <div :class="chat_right(item.type)">
                          <div class="chat_right_div" >
                            <span v-text="item.content" v-if="item.type===100" class="content_message"
                                  style="white-space: pre-wrap !important;"></span>
                            <!--产品类型--->
                            <a :href="$tiyProductUrl(item.content.productCode)" target="_blank" v-if="item.type===300">
                              <div v-if="item.type===300"  style="max-width: 80%" class="content_message">
                                <img :src="item.content.productMainImg" style="width:3rem;float:left;margin-right: 5px;"/>
                                <div style="font-size:12px">
                                  <div class="desc_title" style="font-size: 13px;font-weight: bold">SKU: {{item.content.productCode}}</div>
                                  <div><span  class="base_key" >Price: </span><span class="base_value" v-text="item.content.productPrice"></span></div>
                                  <div><span class="base_key" >Size:</span> <span class="base_value" v-text="item.content.productSize"></span></div>
                                  <div><span class="base_key" style="" v-text="item.content.productName"></span></div>
                                </div>
                              </div>
                            </a>
                            <!--优惠券类型-->
                            <div v-if="item.type===400"  class="content_message">
                              <div class="coupon_parent">
                                <div class="coupon_title" v-show="item.content.discountType===100">
                                  <span class="coupon_title">{{dicountLabel(item.content)}} OFF</span>
                                </div>
                                <div class="coupon_title" v-show="item.content.discountType===200">
                                  <span class="coupon_title">{{dicountLabel(item.content)}} OFF</span>
                                </div>
                                <span class="coupon_desc" >For all products
                          <span v-if="item.content.minAmount!=0">& orders ≥${{item.content.minAmount}}</span></span>
                                <hr style="border:0.6px dashed #bdbdbd;margin:0.3rem 0">
                                <span :class="isNeedWarning(item.content)?'coupon_desc_warning':'coupon_desc'">
                          {{getCouponTip(item.content)}} </span>
                                <div style="text-align: right">
                                  <img src="https://image.fashiontiy.com/imgs/COUNPONS.png" border="0" style="max-width: 40%;float:right" >
                                </div>
                              </div>
                            </div>
                            <!--超链接类型的活动-->
                            <div v-if="item.type===600" class="content_message">
                              <div style="display:flex;align-items:center">
                                <i style="font-size:24px" class="list_key ivu-icon ivu-icon-md-globe"></i>
                                <a :href="item.content" target="_blank" style=" text-decoration: underline;word-wrap:break-word;word-break:break-all;overflow: hidden;">
                                  <span class="y_wordwrap">{{item.content}}</span>
                                </a>
                              </div>
                            </div>
                            <!--订单类型-->
                            <div v-if="item.type===700"  class="content_message">
                              <div style="display:flex;align-items:center">
                                <div style="font-size:12px">
                                  <div><span class="desc_title">订单状态变更</span></div>
                                  <div>
                                    <span class="desc_content">订单{{item.content.serialNumber}}，状态变更为 : </span>
                                    <span class="desc_title" v-text="orderStateDict.filter(orderState => orderState.value == item.content.state)[0].name"></span>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <!--                <span v-text="item.content" v-if="item.type!==200"></span>-->
                            <img :src="item.picUrl" v-if="item.type===200" class="content_message" @click="showImg(item.picUrl)">
                            <!--展厅类型的消息-->
                            <div v-if="item.type===800"  class="content_message" >
                              <div style="display: flex;align-items: center;">
                                <div style="font-size:12px">
                                  <div><span class="desc_title">展厅页面</span><br></div>
                                <div>
                                  <i style="font-size:24px" class="list_key ivu-icon ivu-icon-md-globe"></i>
                                  <a :href="$tiyShowroomUrl(item.content.standRoomUrl)" target="_blank" style="text-decoration: underline;">
                                    {{item.content.standRoomTitle}}
                                  </a>
                                </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div v-text="item.translatedContent" v-if="item.type==100 && !isEmpty(item.translatedContent)" class="chat_desc" style="text-align: right;"></div>
                        <P class="chat_desc" style="text-align: right">
                          <span @click="translateMessage(item)" v-if="item.type===100" style="color:#757575;cursor: pointer;font-size: 12px;margin-left: 0.5rem">翻译</span>
                          <i class="icon ion-md-time" >{{$tiyBJTime(item.createtime)}}</i>
                          <span v-text="item.employeeName"></span>
                          <span :style="messageStateColor(item)" v-text="item.state==100?(item.readed==0?'用户未读':'用户已读'):'已撤回'"></span>
                          <Dropdown placement="bottom-start" trigger="hover"  @on-click="drawn($event,item.id,item.type,item)">
                            <a href="javascript:void(0)">
                              <Icon type="ios-settings" size="12" color="#757575" style="padding: 0.2rem;cursor: pointer"  />
                            </a>
                            <DropdownMenu slot="list"  style="text-align: center" >
                              <DropdownItem v-show="item.state!=200" name="100" >撤回</DropdownItem>
                              <DropdownItem name="200" v-show="item.type!=400">复制</DropdownItem>
                            </DropdownMenu>
                          </Dropdown>
                        </P>
                        <p style="text-align: right;color: #ce93d8" v-if="index>0 && messageList[index-1].direction===1" >
                          {{getTimeStr(item.createtime -messageList[index-1].createtime)}}
                        </p>

                      </div>

                      <div v-if="item.direction===1" class="chat_base_left" style="margin-top:1rem">
                        <div :class="['chat_left',item.type===200?'chat_img':'']">
                          <div v-text="item.content" v-if="item.type===100"></div>
                          <img :src="item.picUrl" v-if="item.type===200" @click="showImg(item.picUrl)">
                        </div>
                        <div v-text="item.translatedContent" v-if="item.type==100 && !isEmpty(item.translatedContent)" class="chat_desc"></div>
                        <div class="chat_desc">
                          <i class="icon ion-md-time">{{$tiyBJTime(item.createtime)}}</i>
                          <span :style="{'color':item.readed==0?'#2196f3': ''}" v-text="item.readed==0?'未读':'已读'"></span>
                          <span @click="translateMessage(item)" v-if="item.type===100" style="color:#757575;cursor: pointer;font-size: 12px;margin-left: 0.5rem">翻译</span>
                          <div v-if="item.sourcePage">
                            <div>
                              <span >来源页面 : {{item.sourcePage}} - </span>
                              <a v-if="item.sourceType == 31 || item.sourceType == 32" @click="showProductSearch(item.sourceValue.productCode)">
                                <span>{{item.sourceValue.productCode}}（点击查询）</span></a>
                              <a v-if="item.sourceType == 41 || item.sourceType == 42" @click="showUserOrders(item.sourceValue.orderId)">
                                <span>{{item.sourceValue.orderId}}（点击查询）</span>
                              </a>
                            </div>
                          </div>
                        </div>
                      </div>

                    </div>
                  </div>
                  <div class="messageNotice" @click="scrollToBottom" v-show="showMessageNotice" style="cursor: pointer;"><button>New Message</button></div>
                </div>
              </td>
            </tr>
            <tr>
              <td style="height: 36px;">
                <Row v-has=tRole.CHAT_2_202 style="border-top: solid 2px #f3f3f6"  >
                  <i-col span="24" class="extended_list" >
                    <Tooltip content="发送图片">
                      <a href="javascript:void(0);"  @click="showSendModal(200)"><Icon type="md-image" size="20" /></a>
                    </Tooltip>
                    <Tooltip content="发送产品">
                      <a href="javascript:void(0);"  @click="showProductModal()"><Icon type="md-basket" size="20" /></a>
                    </Tooltip>
                    <Tooltip content="发送优惠券" v-has=tRole.COUPONS_2_202>
                      <a href="javascript:void(0);"  @click="showCouponModal()"> <Icon type="md-pricetags" size="20" /></a>
                    </Tooltip>
                    <Tooltip content="发送链接">
                      <a href="javascript:void(0);"  @click="showSendModal(600)">  <Icon type="md-globe" size="20" /></a>
                    </Tooltip>
                    <Tooltip content="发送展厅">
                      <a href="javascript:void(0);"  @click="showShowroomModal()">  <Icon type="md-flame" size="20" /></a>
                    </Tooltip>
                    <Tooltip content="新消息邮件通知" placement="right">
                      <Dropdown @on-click="sendEmailDialog">
                        <a href="javascript:void(0);"><Icon type="md-mail" size="20" /></a>
                        <template #list>
                          <DropdownMenu>
                            <DropdownItem name="liveChat">发送LiveChat邮箱</DropdownItem>
                            <DropdownItem name="register">发送注册邮箱</DropdownItem>
<!--                            <DropdownItem>联系邮箱</DropdownItem>-->
                          </DropdownMenu>
                        </template>
                      </Dropdown>
                    </Tooltip>

                    <div style="flex-grow: 1;text-align: right">
                      <Button type="text" style="margin-right: 0;padding: 0 3px" size="small" @click="translateMessages()">一键翻译</Button>
                      <Button type="text" style="margin-right: 0;padding: 0 3px" size="small" @click="clearUnRead()">清空未读</Button>
                      <Button type="text" style="padding: 0 3px" size="small" @click="endDialog()">结束会话</Button>
                    </div>
                  </i-col>
                </Row>
              </td>
            </tr>
            <tr>
              <td style="height: 120px;">
                <Row>
                  <i-col span="24" class="message_text" style="float:right">
                      <Upload
                        multiple
                        paste
                        type="drag"
                        :action="uploadUrl"
                        :data="uploadFolderParam"
                        :with-credentials="false"
                        :on-success="dragUploadImageSuccess"
                        :on-progress="dragUploadImageProgress"
                        :on-error="uploadImageError"
                        :show-upload-list="false"
                        accept="image/png,image/jpeg,image/jpg">
                          <Input v-model="textData" maxlength="2000" show-word-limit type="textarea"
                                    class="message_input" @keyup.ctrl.enter='sendTextMessage' :border="false"
                                    placeholder="可输入文字或者可通过拖拽和粘贴复制上传图片" style="width: 100%;"
                                    @click.native.prevent.stop="">
                          </Input>
                      </Upload>


                    <div class="send_footer">
                      <Button type="primary" :disabled="sendDisabled" :style="{'color':!sendDisabled?'#666':''}"
                              @click="sendTextMessage" :loading="disableSendButton">发送
                      </Button>
                      <span style="color:#bdbdbd">Ctrl+Enter 发送/Enter 换行</span>
                    </div>
                  </i-col>
                </Row>
              </td>
            </tr>
          </table>
        </i-col>
      </Row>



      <Modal
        v-model="status.modalMessage.isShow"
        :title="'发送给 '+messageUserInfo.userCode+'' "
        :styles="{align:'center'}"
        :scrollable=true      >
        <div slot="footer">
          <Button type="primary" style="" @click="sendMessage" >发送
          </Button>
        </div>

        <div class="message_detail">
          <Form ref="paramProductColorSimple" :model="param.productColor" :label-width="100"
                class="modal_newuser_form">
            <Row style="margin: 0.8rem 0rem" v-show="status.modalMessage.type===200">
              <FormItem label="发送图片: " prop="colorImg" >

                <Upload :action="uploadUrl" :data="uploadFolderParam" :with-credentials="false"
                        :on-success="uploadImageSuccess" :on-progress="uploadImageProgress" accept="image/png,image/jpeg,image/jpg" multiple
                        :on-error="uploadImageError" :show-upload-list="false"
                        style="display: inline-block;width:120px;">
                  <Button type="primary" icon="md-cloud-upload" class="tiy_btn">
                    选择图片
                  </Button>
                </Upload>
                <Input v-model.trim="param.messageSendParam.picUrl" style="display: none"></Input>
              </FormItem>
              <FormItem v-if="''!= param.messageSendParam.picUrl">
                <Card class="item_card"  style="max-width:180px">
                  <Img :src="yunPath+ param.messageSendParam.picUrl" width="100%" style="border:dashed 1px #bdbdbd"
                       @click="showImage(yunPath + param.messageSendParam.picUrl)"/>
                  <div slot="extra">
                    <span @click="removeImage(item)">
                        <Button type="text" shape="circle" size="small" icon="ios-close-circle" style="color: #9c27b0"></Button>
                      </span>
                  </div>
                </Card>
              </FormItem>
            </Row>
            <Row style="margin: 0.8rem 0rem" v-show="status.modalMessage.type===600">
              <i-col span="24">
              <FormItem label="链接: " prop="content">
                <Input v-model.trim="param.messageSendParam.content" type="textarea" :rows="4" placeholder="Enter something..." />
              </FormItem>
              </i-col>
            </Row>
          </Form>
        </div>
      </Modal>

      <!-- 图片 -->
      <Modal v-model="isShowImgDialog"
             title=""
             :styles="{align:'center',width:'80%'}"
             :scrollable=true>
        <div slot="footer"></div>
        <div align="center"><Img :src="imgNeedToShow" style="max-width: 800px;" /></div>
      </Modal>
    </div>
    <a-ProductSelectList  :productListShow="isShowProductList"  @hideProductList="hideProductList()" @receiveProductData="receiveProductData" v-show="isShowProductList" ></a-ProductSelectList>
    <a-CouponSelectList  :couponListShow="isShowCouponList"  @hideCouponList="hideCouponList()" @receiveCouponData="receiveCouponData" v-show="isShowCouponList" ></a-CouponSelectList>
    <!-- 选择展厅 -->
    <Modal v-model="isShowroomList" title="关联展厅" :mask-closable="false" :width="1000">
      <showroom-selection  @query-list="queryShowroomList" :is-single-select="true" :limit-platforms="[]"></showroom-selection>
      <div slot="footer">
        <Button @click="hideShowroomModal()">取消</Button>
        <Button type="primary" @click="selectedShowroom()">确定</Button>
      </div>
    </Modal>

    <Modal
      v-model="status.modalAction.isShow"
      title="确认" @on-ok="readMessage" :mask-closable="false">
      是否将消息置为已读？
    </Modal>

    <Modal v-model="status.modalSearchInfo.isShow" title="信息查询"
           :styles="{top: '20px',bottom:'20px',width:'80%',}" >
      <Row style="padding-top: 10px;text-align: left" v-show="status.modalSearchInfo.showTableType == 1 || status.modalSearchInfo.showTableType == 2">
        <i-col span="10">
          <span>
            <Input v-model.trim="param.searchInfoParam.productCode" placeholder="输入产品编码"
                   v-show="status.modalSearchInfo.showTableType == 1" clearable ></Input>
            <Input v-model.trim="param.searchInfoParam.serialNumber" placeholder="输入订单编号"
                   v-show="status.modalSearchInfo.showTableType == 2" clearable ></Input>
          </span>
        </i-col>
        <i-col span="6">
          <Button type="primary" style="margin-right: 10px;margin-left: 10px" icon="md-search"
                  v-show="status.modalSearchInfo.showTableType == 1" @click="searchProduct">查询产品</Button>
          <Button type="primary" style="margin-right: 10px;margin-left: 10px" icon="md-search"
                  v-show="status.modalSearchInfo.showTableType == 2" @click="searchOrder" >查询订单</Button>
        </i-col>
      </Row>
      <Row style="padding-top: 10px;text-align: left"v-show="status.modalSearchInfo.showTableType == 3">
        <i-col span="10">
          <b>总重量: {{tData.cartWeightCount}}</b>&nbsp;&nbsp;
        </i-col>
        <i-col span="6">
          <b>总金额: {{tData.cartPriceCount}}</b>
        </i-col>
      </Row>
      <Row style="padding-top: 10px;text-align: left">
        <!--表格和分页-->
        <Table stripe border :context="this" :columns="productTable" :data="productList"
               v-show="status.modalSearchInfo.showTableType == 1" no-data-text="暂无数据" ></Table>
        <Table stripe border :context="this" :columns="orderTable" :data="orderList"
               v-show="status.modalSearchInfo.showTableType == 2" no-data-text="暂无数据" ></Table>
        <Table stripe border :context="this" :columns="cartTable" :data="cartList"
               v-show="status.modalSearchInfo.showTableType == 3" no-data-text="暂无数据" ></Table>
        <Table stripe border :context="this" :columns="recordTable" :data="recordList"
               v-show="status.modalSearchInfo.showTableType == 4" no-data-text="暂无数据" ></Table>
      </Row>
      <Row style="padding-top: 10px;text-align: left">
        <Page :total="searchInfoPage.total" :page-size="searchInfoPage.stepNumber" :current="searchInfoPage.currentPage"
              @on-change="changeSearchPage"  show-elevator/>
      </Row>
    </Modal>

    <Modal
      v-model="statusAddEdit.modalModify.isShow"
      title=""  :mask-closable="false"
      :styles="{top: '20px',bottom:'20px',width:'85%'}">
      <a-productAddEdit ref="AProductAddEdit"></a-productAddEdit>
      <div slot="footer"></div>
    </Modal>

    <!--查看订单详情-->
    <a-OrderDetail ref="orderDetail" @hideDetail="hideOrderDetail()" :orderId="orderId" :detailShow="isShowDetail" v-show="isShowDetail" ></a-OrderDetail>

    <Modal v-model="status.modalAssignUser.isShow" title="选择负责人" :mask-closable="false"
           :styles="{top: '20px',bottom:'20px',width:'40%',}" :scrollable=false @on-ok="assignToEmployee()" >
      <!--表格和分页-->
      <Row >
        <i-col span="4">&nbsp;</i-col>
        <i-col span="16">
          <SearchCustomerService ref="employeeSearch" @choose-customer-service="chooseCustomerService"></SearchCustomerService>
        </i-col>
        <i-col span="4">&nbsp;</i-col>
      </Row>
    </Modal>
    <Modal v-model="status.modalStatusChange.isShow" title="会话状态" :mask-closable="false"
           @on-ok="complete" style="text-align: center">
      <Select v-model="statusParam.state"  style="max-width: 70%">
        <Option v-for="item in messageStatusDict" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
    </Modal>

    <Modal v-model="status.modalModifyStatusNote.isShow" title="修改备注" :mask-closable="false"
           @on-ok="saveStatusNote()" style="text-align: center">
      <Input type="textarea" clearable v-model="param.noteParam" :rows="10"></Input>
    </Modal>

    <!-- 显示产品货源信息 -->
    <Modal v-model="status.modalProductSupply.isShow" title="产品货源" footer-hide :width="800">
      <List border style="margin-top: 10px;">
        <template v-if="tData.productSupplyList.length == 0">
          <ListItem><div style="width: 100%; text-align: center;">暂无数据</div></ListItem>
        </template>
        <template v-else>
          <ListItem v-for="(item, index) in tData.productSupplyList" :key="index" class="list-item">
            <div class="item-top">
              <p style="font-weight: bold;">
                <Tag :color="getSupplyColor(item.state)">{{getSupplyState(item.state)}}</Tag>
                {{item.name}}
              </p>
            </div>
            <div class="item-content">
              <div>
                <KeyValueView title="采购渠道" :value="getSupplySourceType(item.source)"></KeyValueView>
                <KeyValueView title="采购链接">
                  <a :href="item.url" target="_blank">点击访问</a>
                </KeyValueView>
              </div>
              <div>
                <KeyValueView title="货源店铺" :value="item.shopName"></KeyValueView>
                <KeyValueView title="参考价格" :value="item.referencePrice"></KeyValueView>
              </div>
              <div v-if="isCollectionLibSupply(item.source)">
                <KeyValueView title="采集库产品编号" :value="item.productCollectionCode"></KeyValueView>
              </div>
            </div>
          </ListItem>
        </template>
      </List>
    </Modal>

    <Modal v-model="status.modalEmail.isShow" title="用户邮箱" :mask-closable="false">
      <Form ref="emailForm" :label-width="80" :model="param.userEmailParam" :show-message="false">
        <FormItem label="邮箱" prop="email" required>
          <Input type="email" v-model="param.userEmailParam.email"></Input>
        </FormItem>
        <FormItem label="备注" prop="note">
          <Input type="textarea" v-model="param.userEmailParam.note"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="hideEmailModal()">取消</Button>
        <Button type="primary" @click="saveUserEmail()">保存</Button>
      </div>
    </Modal>

    <!-- 发送邮件 -->
    <Modal v-model="status.modalSendEmail.isShow" title="发送提醒邮件"
      :mask-closable="false" :styles="{top: '20px',bottom:'20px',width:'85%'}">
      <send-email v-bind:receiveUser="status.modalSendEmail.users" :is-send="false" v-bind:isRefresh="status.modalSendEmail.isShow"
                       v-bind:text="status.modalSendEmail.emailContent" v-bind:title="status.modalSendEmail.emailTitle"
                       v-on:listenSendEmailEvent="sendSuccess"  ref="SendEmail"></send-email>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<!--javascript 代码-->
<script>
    import ICol from "view-design/src/components/grid/col";
    import tiyData from "./js/chatMessageDetail/chat_message_detail_data";
    import SearchEmployee from "../widgets/SearchEmployee";
    import SendEmail from "../email/SendEmailTemplate.vue";
    import {
      init,
      webList,
      chatSendMessage,
      getMessageUserInfo,
      deleteMessagePic,
      searchProduct,
      searchOrder,
      searchCart,
      searchRecord,
      getMessageStatus,
      updateStatusTags,
      updateStatusNote,
      endDialog,
      getTabList,
      initQueryShowroom,
      queryShowroomList,
      sendShowroomData, queryProductSupplyList, saveUserContactEmail, getUserContactEmail
    } from "./js/chatMessageDetail/chat_message_detail_funs"
    import ApiBase from "../../api/moudles/ApiBase";
    import AProductSelectList from "../product/ProductSelectList.vue"
    import ACouponSelectList from "../coupons/CouponSelectList.vue"
    import AProductAddEdit from "../product/ProductAddEdit.vue"
    import ShowroomSelection from "../stands/showroomSelect/ShowroomSelection";
    import tiyAddEditData from "../product/js/list/add_edit_data"
    import {
        modifyProduct,
    } from  "../product/js/list/add_edit_fun"
    import AOrderDetail from "../order/OrderDetail.vue"
    import KeyValueView from "../widgets/KeyValueView";
    import {isEmpty, translateText} from "../js/commonUtils";
    import SearchCustomerService from "../widgets/SearchCustomerService";
    export default {
        name: "ChatMessageDetail",
        props: {
            detailShow: {
                type: Boolean,
                default: false,
                require: true
            },
            userId: {
                type: String,
                default: '',
                require: true
            },
          direction:{
            type: String,
            default: 'row',
            require: false
          }
        },

        components: {ICol, AProductSelectList, ACouponSelectList, AProductAddEdit, AOrderDetail, SearchEmployee, ShowroomSelection,
            KeyValueView, SearchCustomerService, SendEmail},

        data() {
            return {
                tRole: {
                    CHAT_2_202: "CHAT-2-202",
                    CHAT_2_203: "CHAT-2-203",
                    CHAT_2_205: "CHAT-2-205",
                    COUPONS_2_202:"COUPONS-2-202"
                },
                isShow: false,
                param: tiyData.tParams,
                tData:tiyData.tData,
                preLoading: false,
                messageList: tiyData.tData.messageList,
                user: {},
                messageContent: '',
                status: tiyData.tStatus,
                page: tiyData.tPage,
                uploadUrl: this.$apiImage.uploadMessagePic(),
                yunPath: this.$store.getters.imgPrefix,
                imgNeedToShow: '',
                isShowImgDialog: false,
                messageUserInfo: tiyData.tData.messageUserInfo,
                isShowProductList: false,
                isShowroomList: false,
                isShowCouponList: false,
                productData: {},
                showroomData:{},
                couponData: {},
                textData: '',
                isPaste: false,
                isLoading: false,
                refresh: false,
                refreshTime: 60,
                timer: '',
                showLoadingPre: true,
                showMessageNotice: false,
                hasPre:true,
                disableSendButton:false,
                productTable: tiyData.productTable(this),
                productList: tiyData.tData.productList,
                statusAddEdit:tiyAddEditData.tStatus,
                orderList: tiyData.tData.orderList,
                orderTable: tiyData.orderTable(this),
                orderId:'',
                isShowDetail:false,
                //字典 订单状态
                orderStateDict: this.$store.getters.dictionaries.orderStateDict,
                searchInfoPage: tiyData.searchInfoPage,
                loginTypeDict: this.$store.getters.dictionaries.loginTypeDict,
                cartList: tiyData.tData.cartList,
                cartTable: tiyData.cartTable(this),
                recordList: tiyData.tData.recordList,
                recordTable: tiyData.recordTable(this),
              collapseValue: "-1",
              tagList: [],
              selectedTags:[],
              statusParam: tiyData.tParams.statusParam,
              messageStatusDict:[
                {  value: 600,label: '会话未开启'},
                {  value: 610,label: '会话已开启'},
                {  value: 100,label: '处理-已受理'},
                {  value: 200,label: '处理-沟通中'},
                {  value: 300,label: '处理-资源协调中'},
                {  value: 400,label: '处理-受阻'},
                {  value: 500,label: '会话关闭'}
              ],
              showBaseInfoMobile:false
            }
        },
        computed: {
            uploadFolderParam() {
                let requestMsg = ApiBase.createRequestMsg({folder: "message_pic"});
                return {requestMsg: JSON.stringify(requestMsg)};
            },
            deviceTypeLabel() {
                let label = "未知";
                if (this.messageUserInfo.deviceType == 1) {
                    label = "Android";
                } else if (this.messageUserInfo.deviceType == 2) {
                    label = "IOS";
                } else if (this.messageUserInfo.deviceType == 3) {
                    label = "PC";
                }
                return label;
            },
            registerTypeLabel() {
                let label = "未知";
                for(let i  = 0; i < this.loginTypeDict.length; i++){
                    let item = this.loginTypeDict[i];
                    if (item.value === this.messageUserInfo.registerType) {
                        label = item.name;
                        break;
                    }
                }
                return label;
            },
            sendDisabled(){
                return this.textData.trim()==''||this.disableSendButton;
            },
          messageStatusLabel(){
            return function(type){
              var targetItem = this.messageStatusDict.find(function (item,index){
                return item.value === type;
              });
              if (targetItem===undefined){
                return "无"
              }else
                return targetItem.label;
            }
          }
        },
        methods: {
          isEmpty(val) {
            return isEmpty(val);
          },
          switchMobileInfo(){
            this.showBaseInfoMobile = !this.showBaseInfoMobile;
          },
            showImg(path) {
                this.isShowImgDialog = true;
                this.imgNeedToShow = path;
            },
            closeImg() {
                this.isShowImgDialog = false;
                this.imgNeedToShow = '';
            },
            search(toBottom) {
                init(this, tiyData);
                webList(this, tiyData,toBottom,"down");
            },
            showSendModal(type) {
                tiyData.tStatus.modalMessage.isShow = true;
                tiyData.tStatus.modalMessage.type = type;
                tiyData.tParams.messageSendParam.content = '';
                tiyData.tParams.messageSendParam.picUrl = "";
                tiyData.tParams.messageSendParam.type = type;
            },
            sendTextMessage() {
              tiyData.tParams.messageSendParam.content = this.textData;
              tiyData.tParams.messageSendParam.type = 100;
              this.sendMessage();
            },
            sendMessage() {
                chatSendMessage(this, tiyData);
            },
            uploadImageSuccess(response, file, fileList) {
                this.$Spin.hide();
                if(response.success){
                    tiyData.tParams.messageSendParam.picUrl = response.result;
                } else {
                    this.$Message.error("上传图片失败！" + response.errorMessage);
                }
            },
            dragUploadImageSuccess(response, file, fileList) {
              this.$Spin.hide();
              if(response.success){
                tiyData.tParams.messageSendParam.picUrl = response.result;
                this.sendMessage();
              } else {
                this.$Message.error("上传图片失败！" + response.errorMessage);
              }
            },
            uploadImageError(error, file, fileList) {
                tiyData.tParams.messageSendParam.picUrl = "";
                tiyData.tParams.messageSendParam.ossId = "";
                this.$Spin.hide();
                this.$Message.error("上传图片失败！" + error);
            },
            uploadImageProgress(event, file, fileList) {
                this.$Spin.show();
            },
            dragUploadImageProgress(event, file, fileList) {
              this.textData = this.textData.replace(file.name, "");
              tiyData.tParams.messageSendParam.type = 200;
              this.$Spin.show();
            },
            showImage(imageUrl) {
                tiyData.tStatus.modalImage.url = imageUrl;
                tiyData.tStatus.modalImage.isShow = true;
            },
            removeImage() {
                deleteMessagePic(this, tiyData);
            },
            handleReachEdge() {//上一页
                this.preLoading = true;
                this.showLoadingPre = false;
                webList(this, tiyData,false,"up");
            },

            scrollToBottom() {
                this.$nextTick(() => {
                    let div = document.getElementById('chat_content');
                    div.scrollTop = div.scrollHeight;
                })
            },
            modalStatus(status) {
                if (!status ) {
                    if (this.timer != null) {
                      clearInterval(this.timer);
                    }
                    /*let hasUnReaded = false;
                  for(let i = 0; i < tiyData.tData.messageList.length; i++){
                      let item = tiyData.tData.messageList[i];
                      if(item.readed !== 1 && item.direction == 1){ //有未读的用户消息
                          hasUnReaded = true;
                          break;
                      }
                  }
                  if(hasUnReaded){
                      this.$Modal.confirm({
                          title: "提示",
                          content:
                              "<div><span>是否需要</span><span style='color:#ef4836'>将消息置为已读</span><span>？</span></div>",
                          okText: "确定",
                          cancelText: "取消",
                          closable: true,
                          zIndex: 1,
                          onOk: () => {
                              this.readMessage();
                              this.$emit("hideDetail");
                          },
                          onCancel: () => {
                              this.$emit("hideDetail");
                          }
                      })
                  } else {
                      this.$emit("hideDetail");
                  }*/
                  this.$emit("hideDetail");
                }
            },
            showProductModal() {
                this.isShowProductList = true;
            },
            showCouponModal() {
                this.isShowCouponList = true;
            },
            showShowroomModal(){
              initQueryShowroom(this);
              this.isShowroomList = true;
            },
            hideProductList() {
                this.isShowProductList = false;
            },
            hideCouponList() {
                this.isShowCouponList = false;
            },
            hideShowroomModal(){
                this.isShowroomList = false;
            },
            receiveProductData(product) {
                this.productData.productId = product.id;
                this.productData.productName = product.name;
                this.productData.productCode = product.code;
                this.productData.productMainImg = product.productImg;
                this.productData.productShowImg = product.productShowImg;
                this.productData.productUrl = product.linkUrl;
                var price = "$" + product.minPrice;
                if (product.minPrice != product.currentPrice) {
                    price = "$" + product.minPrice + ' - ' + "$" + product.currentPrice
                }
                this.productData.productPrice = price;
                var size = product.productSize;
                var sizeNameArray = new Array();
                if (size != null && size.length > 0) {
                    size.forEach(function (item, index) {
                        sizeNameArray.push(item.name);
                    })
                } else {
                    sizeNameArray.push("One Size");
                }
                this.productData.productSize = sizeNameArray.join(" / ");
                //发送产品
                tiyData.tParams.messageSendParam.content = JSON.stringify(this.productData);
                tiyData.tParams.messageSendParam.type = 300;
                chatSendMessage(this, tiyData);
            },
            queryShowroomList() {
                queryShowroomList(this);
            },
            selectedShowroom(){
                this.hideShowroomModal();
                sendShowroomData(this, tiyData);
            },
            /**
             * 发放优惠券
             * @param self
             * @param tiyData
             */
            receiveCouponData(couponDefine) {
                var self = this;
                self.$Spin.show();
                let data = {"defineId": couponDefine.id, "title": couponDefine.title};
                let userIds = [this.userId];
                // userIds.push(this.userId);
                data.userIds = userIds;
                self.$apiCoupon.distributeCoupon(data).then(function (response) {
                    self.$Spin.hide();
                    if (response.success) {
                        self.$Message.info("优惠券发放成功！");
                        self.search(true);
                    } else {
                        self.$Message.error(response.errorMessage);
                    }
                });
            },
            isNeedWarning(coupon) {
                var now = new Date();
                var next3Day = new Date(new Date().setDate(new Date().getDate() + 3));
                var result = coupon.startTimeStamp >= now.getTime() || next3Day.getTime() > coupon.expiredTimeStamp;
                return result;
            },
            showRead() {
                tiyData.tStatus.modalAction.isShow = true;
            },
            readMessage() {
                let self = this;
                self.$Spin.show();
                let data = {"userId": self.userId};
                self.$apiChat.readMessage(data).then(function (response) {
                    self.$Spin.hide();
                    if (response.success) {
                        if (response.result > 0) {
                            tiyData.tData.messageList.forEach(function (item, index) {
                                if (item.direction == 1 && item.readed == 0) {
                                    item.readed = 1;
                                    tiyData.tData.messageList.splice(index, 1, item);
                                }
                            });
                            self.$emit("refreshList");//刷新列表
                        }
                        self.$Message.info("已设置" + response.result + "条数据为已读");
                    } else {
                        self.$Message.error(response.errorMessage);
                    }
                });

            },
            chat_right(type) {
                if (type == 200) {
                    return 'chat_right chat_img';
                } else if (type == 400) {
                    return 'chat_right chat_coupon';
                } else if (type == 100) {
                    return 'chat_right chat_text';
                } else {
                    return 'chat_right'
                }
            },
            drawn(name, id,type,item){
                var self  = this;
                //撤回消息
                if(name=="100"){
                    //发送撤回请求
                    self.$Modal.confirm({
                        title: "提示",
                        content:
                            "<div><span>是否</span><span style='color:#ef4836'>撤回该消息</span><span>？</span></div>",
                        okText: "确定",
                        cancelText: "取消",
                        closable: true,
                        zIndex: 1,
                        onOk: () => {
                            self.$Spin.show();
                            let data = {"messageId": id,"userId": self.userId};
                            self.$apiChat.recallMessage(data).then(function (response) {
                                if (response.success) {
                                    self.search(false);
                                } else {
                                    self.$Message.error(response.errorMessage);
                                }
                            });
                        },
                        onCancel: () => {
                        }
                    })
                    //copy
                }else if(name=='200'){
                    var input = document.createElement('input');
                    document.body.appendChild(input);
                    if(type==100 || type==600){
                        input.setAttribute('value', item.content);
                    }else if(type==200){
                        input.setAttribute('value', item.picUrl);

                    }else if(type==300){
                        input.setAttribute('value', self.$tiyProductUrl(item.content.productCode));
                    }
                    input.select();
                    if (document.execCommand('copy')) {
                        document.execCommand('copy');
                    }
                    document.body.removeChild(input);
                }

            },
            dicountLabel(coupon) {
                var reLabel = "";
                if (coupon.discountType == 100) {
                    reLabel = "$" + coupon.amount;
                } else if (coupon.discountType == 200) {
                    reLabel = (100 - coupon.amount * 100).toFixed(1) + "%";
                }

                return reLabel;

            },
            getCouponTip(coupon) {
                var expiredTime = coupon.expiredTimeStamp;
                var hasExpired = coupon.expiredTimeStamp <= new Date().getTime();
                var fromFuture = coupon.startTimeStamp > new Date().getTime();

                if (coupon.isUsed) {
                    return "Has been used on " + this.$tiyBJTime(coupon.usedTimeStamp);
                } else if (hasExpired) {
                    return "Has been expired on " + this.$tiyBJTime(expiredTime);
                } else if (fromFuture) {
                    return "Useable from " + this.$tiyBJTime(coupon.startTimeStamp);
                } else {
                    return "Will expired on " + this.$tiyBJTime(expiredTime);
                }
            },
            messageStateColor(message) {
                let color = '';
                if(message.state==200){
                    color="#e81e63";
                }else {
                    if(message.readed==0){
                        color = "#2196f3"
                    }
                }
                return {'color':color}
            },
            showProductSearch(productCode){
                this.initSearchInfo(1);
                tiyData.tData.productList.splice(0, tiyData.tData.productList.length);
                tiyData.tParams.searchInfoParam.userId = "";
                tiyData.tParams.searchInfoParam.serialNumber = "";
                if(productCode){
                    tiyData.tParams.searchInfoParam.productCode = productCode;
                    this.searchProduct();
                } else {
                    tiyData.tParams.searchInfoParam.productCode ="";
                }
                tiyData.tStatus.modalSearchInfo.isShow = true;
            },
            searchProduct(){
                if(!tiyData.tParams.searchInfoParam.productCode){
                    this.$Message.error("请输入产品编码");
                    return;
                }
                tiyData.tParams.searchInfoParam.userId = "";
                tiyData.tParams.searchInfoParam.serialNumber = "";
                searchProduct(this, tiyData);
            },
            editItem(index) {
                modifyProduct(this, tiyAddEditData, tiyData.tData.productList[index].id, true);
            },
            searchOrder(){
                // if(!tiyData.tParams.searchInfoParam.serialNumber){
                //     this.$Message.error("请输入订单编号");
                //     return;
                // }
                searchOrder(this, tiyData);
            },
            showOrderDetail(id){
                this.orderId = id;
                this.isShowDetail = true;
            },
            hideOrderDetail(){
                this.isShowDetail = false;
                this.orderId = "";
            },
            changeSearchPage(page){
                tiyData.searchInfoPage.currentPage = page;
                switch(tiyData.tStatus.modalSearchInfo.showTableType){
                    case 1:
                        searchProduct(this, tiyData);
                        break;
                    case 2:
                        searchOrder(this, tiyData);
                        break;
                    case 3:
                        searchCart(this, tiyData);
                        break;
                    case 4:
                        searchRecord(this, tiyData);
                        break;
                    default:
                        break;
                }
            },
            showUserOrders(serialNumber){
                this.initSearchInfo(2);
                tiyData.tParams.searchInfoParam.productCode ="";
                tiyData.tParams.searchInfoParam.userId = this.userId;
                if(serialNumber){
                    tiyData.tParams.searchInfoParam.serialNumber = serialNumber;
                } else {
                    tiyData.tParams.searchInfoParam.serialNumber = "";
                }
                searchOrder(this, tiyData);
                tiyData.tStatus.modalSearchInfo.isShow = true;
            },
            showUserCart(){
                tiyData.tParams.searchInfoParam.productCode ="";
                tiyData.tParams.searchInfoParam.userId = this.userId;
                tiyData.tParams.searchInfoParam.serialNumber = "";
                this.initSearchInfo(3);
                this.$ySpliceAll(tiyData.tData.cartList);
                searchCart(this, tiyData);
                tiyData.tStatus.modalSearchInfo.isShow = true;
            },
            showUserRecords(){
                tiyData.tParams.searchInfoParam.productCode ="";
                tiyData.tParams.searchInfoParam.userId = this.userId;
                tiyData.tParams.searchInfoParam.serialNumber = "";
                this.initSearchInfo(4);
                this.$ySpliceAll(tiyData.tData.recordList);
                searchRecord(this, tiyData);
                tiyData.tStatus.modalSearchInfo.isShow = true;
            },
            initSearchInfo(type){
                tiyData.searchInfoPage.stepNumber = 40;
                tiyData.searchInfoPage.currentPage = 1;
                tiyData.tStatus.modalSearchInfo.showTableType = type;
            },
            saveStatusTags() {
                for(let tag of this.selectedTags) {
                  if(tag==null || tag.trim()==="") {
                    this.$Message.error("不能添加空标签！")
                    return;
                  }
                }
                tiyData.tData.messageStatus.tags = JSON.stringify(this.selectedTags);
                updateStatusTags(this, tiyData);
            },
            saveStatusNote() {
                updateStatusNote(this, tiyData);
            },
            showStateModal(userId, state){ //修改状态窗口
              tiyData.tParams.statusParam.userId = userId;
              tiyData.tParams.statusParam.state = state;
              tiyData.tStatus.modalStatusChange.isShow = true;
            },
            showAssign(userId){ //显示分配用户窗口
              //单条分配
              if(userId){
                tiyData.tStatus.modalAssignUser.isShow = true;
                tiyData.tParams.messageStatusParam.userId = userId;
              }
              this.$refs['employeeSearch'].clearSelectedEmployee();
            },
            chooseEmployee(value){
              tiyData.tParams.messageStatusParam.employeeId = (value==null?null:value.id);
            },
          chooseCustomerService(value) {
            tiyData.tParams.messageStatusParam.employeeId = (value==null?null:value.employeeId);
              tiyData.tParams.messageStatusParam.employeeName = (value==null?null:value.userName);
          },
          assignToEmployee(){ //分配用户给指定员工
            var self = this;
            if(!tiyData.tParams.messageStatusParam.employeeId){
              this.$Message.error("请选择负责人！");
              return;
            }
            //
            self.$Spin.show();
            self.$apiChat.assignToEmployee({
              "employeeId":tiyData.tParams.messageStatusParam.employeeId,
              "employeeName":tiyData.tParams.messageStatusParam.employeeName,
              "userId":self.userId,
              "userEncodeName":tiyData.tData.messageUserInfo.userCode
            }).then(response => {
              self.$Spin.hide();
              if (response.success) {
                getMessageStatus(this, tiyData);
                self.$emit("refreshList");
                self.$Message.success("分配负责人成功！");
              } else {
                self.$Message.error(response.errorMessage);
              }
            });
          },
          complete(){
            var self = this;
            self.$Spin.show();
            self.$apiChat.changeMessageStatus({
              // "statusId":tiyData.tParams.statusParam.statusId,
              "userId": this.userId,
              "state":tiyData.tParams.statusParam.state,
            }).then(response => {
              self.$Spin.hide();
              if (response.success) {
                getMessageStatus(this, tiyData);
                self.$emit("refreshList");
                self.$Message.success("会话状态修改成功！");
              } else {
                self.$Message.error(response.errorMessage);
              }
            });
          },
          showNoteModal() {
              tiyData.tParams.noteParam = tiyData.tData.messageStatus.note;
              tiyData.tStatus.modalModifyStatusNote.isShow = true;
          },
          endDialog() {
            let self = this;
            this.$Modal.confirm({
              title: "确认",
              content: "结束会话将同时清空所有未读消息，确定结束吗？",
              okText: "确定",
              cancelText: "取消",
              onOk: () => {
                endDialog(self, tiyData);
              },
            });
          },
          clearUnRead() {
              this.$Modal.confirm({
                title: "确认",
                content: "确定清空所有未读消息记录吗？该操作不会关闭会话,如果您的服务已经结束,请结束会话.",
                okText: "确定",
                cancelText: "取消",
                onOk: () => {
                  this.readMessage();
                  // this.$emit("hideDetail");
                },
              });
          },
          saveUserTab(){
            let self=this;
            self.$Spin.show();
            let params = {
              tabIds: self.messageUserInfo.tabId,
              type:2,
              mappingId: self.userId,
            };
            self.$apiOther.updateTabMappings(params).then(response => {
              self.$Spin.hide();
              if(response.success) {
                self.$Message.success("保存成功");
              }else{
                self.$Modal.error(response.errorMessage);
              }
            });
          },
          showProductSupply(cartProduct) {
              this.status.modalProductSupply.isShow = true;
              queryProductSupplyList(this, tiyData, cartProduct);
          },
          getTimeStr(offset){
              var str = "距离用户发消息: ";
            let days = Math.floor(offset / (24 * 3600 * 1000)); // 计算出天数
            if (days>0){
              str+=days+"天";
            }
            let leavel = offset % (24 * 3600 * 1000); // 计算天数后剩余的时间
            let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
            if (hours>0){
              str+=hours+"小时";
            }
            let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
            let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
            return str += minutes + '分';
          },
          getSupplyColor(state) {
            switch (state) {
              case 1:
                return "success";
              case 2:
                return "gray";
              default:
                return "info";
            }
          },
          getSupplyState(state) {
            switch (state) {
              case 1:
                return "已上架";
              case 2:
                return "已下架";
              default:
                return "";
            }
          },
          getSupplySourceType(source) {
            switch (source) {
              case 1:
                return "1688";
              case 2:
                return "淘宝";
              case 3:
                return "拼多多";
              case 4:
                return "线下";
              case 5:
                return "产品采集库";
              default:
                return "";
            }
          },
          isCollectionLibSupply(source) {
            return source == 5;
          },
          showEmailModal() {
            this.status.modalEmail.isShow = true;
            this.$refs.emailForm.resetFields();
            this.param.userEmailParam.id = this.tData.userEmail.id;
            this.param.userEmailParam.userId = this.tData.userEmail.userId;
            this.param.userEmailParam.note = this.tData.userEmail.note;
            this.param.userEmailParam.email = this.tData.userEmail.email;
            this.param.userEmailParam.createtime = this.tData.userEmail.createtime;
          },
          hideEmailModal() {
            this.status.modalEmail.isShow = false;
          },
          saveUserEmail() {
            this.param.userEmailParam.userId = this.userId;
            saveUserContactEmail(this, tiyData);
          },
          containsEnglish(text) {
            let regex = /[a-zA-Z]/;
            return regex.test(text);
          },
          translateMessage(item) {
            let params = {text: item.content, target: "zh"};
            translateText(this, params, function (result) {
              item.translatedContent = result;
            });
          },
          translateMessages() {
            if(this.messageList.length > 0) {
              this.translateOneMessage(0);
            }
          },
          translateOneMessage(index) {
            if(index < this.messageList.length) {
              let self = this;
              let item = this.messageList[index];
              if(item.type === 100) {
                let params = {text: item.content, target: "zh"};
                translateText(this, params, function (result) {
                  item.translatedContent = result;
                  self.translateOneMessage(++index);
                });
              }else{
                self.translateOneMessage(++index);
              }
            }
          },
          sendEmailDialog(targetEmail) {
              this.$ySpliceAll(this.status.modalSendEmail.users);
              let length = tiyData.tData.messageList.length;
              let msg = tiyData.tData.messageList[length - 1];
              // debugger;
              if(!length || !msg){
                  this.$Message.error("没有需要提醒的站内信内容！");
                  return;
              }

              if(msg.direction == 1){
                  let find = false;
                  for(let i = length - 2; i >= 0; i--){
                      msg = tiyData.tData.messageList[i];
                      if(msg.direction == 2){
                          find = true;
                          break;
                      }
                  }
                  if(!find){
                      this.$Message.error("没有需要提醒的站内信内容！");
                      return;
                  }
              }

              if(msg.readed){
                  this.$Message.error("用户已经读取此消息。");
              }

              let email = "";
              if(targetEmail == "register") {//发送给注册邮箱
                if(isEmpty(tiyData.tData.messageUserInfo.email)) {
                  this.$Message.error("用户没有保留注册邮箱，不能发送提醒邮件！");
                  return;
                }else{
                  email = tiyData.tData.messageUserInfo.email;
                }
              }
              if(targetEmail == "liveChat") {//发送LiveChat邮箱
                if(isEmpty(tiyData.tData.userEmail.id)) {
                  this.$Message.error("用户没有保留LiveChat邮箱，不能发送提醒邮件！");
                  return;
                }else{
                  email = tiyData.tData.userEmail.email;
                }
              }
              let user = {
                "id": this.userId,
                "encodeName": this.messageUserInfo.userCode,
                "contactEmail":email
              };
              this.status.modalSendEmail.users.push(user);
              this.status.modalSendEmail.email = email;
              let emailContent =  "<br><br>"+"More messages please check in live chat: "+this.$store.state.login.webDomain;
              switch(msg.type){ //暂时只发送文本类型的提醒
                case 100:
                  emailContent ="Part of message: <br>"+msg.content+ emailContent ;
                  break;
                default:
                  break;
              }
              this.status.modalSendEmail.emailContent = emailContent;
              this.status.modalSendEmail.isShow = true;
          },
          sendSuccess(isSuccess){
              if(isSuccess){
                this.status.modalSendEmail.isShow = false;
              }
          },
        },
        watch: {
            messageList() {
            },
            detailShow: function (val) {
                let self = this;
                if (val) {
                    init(this, tiyData);
                    this.selectedTags.splice(0);
                    tiyData.tData.messageList.splice(0, tiyData.tData.messageList.length)
                    getMessageUserInfo(this, tiyData);
                    getMessageStatus(this, tiyData);
                    getUserContactEmail(this, tiyData);
                    getTabList(this,tiyData);
                    webList(this, tiyData,true,"down");
                    this.refresh = true;//自动刷新列表
                    this.hasPre = true; // 防止其它会话设置后影响其它会话

                    let contentDiv = document.getElementById('chat_content');
                    contentDiv.addEventListener("scroll", function(){
                        if(contentDiv==null){
                            return;
                        }
                        let height =parseInt(contentDiv.scrollHeight-contentDiv.scrollTop-contentDiv.clientHeight);
                        if(height<50){
                            self.showMessageNotice = false;
                        }
                    });
                } else {
                    this.refresh = false;//自动刷新列表
                    clearInterval(this.timer);
                }
                this.isShow = val;
            },
            refresh(newName, oldName) {
                let self = this;
                if (newName) {
                    self.timer = setInterval(function () {
                        if (self.refreshTime == 1) {
                            webList(self, tiyData,false,"down");
                        }
                        self.refreshTime--;
                    }, 1000)
                } else {
                    self.refreshTime = 60;
                    clearInterval(self.timer);
                }
            },
        },
        mounted() {

        },
        created() {

        },
        beforeDestroy() {
          if(this.timer != null) {
            clearInterval(this.timer);
          }
        }
    }
</script>

<!--css样式-->
<style scoped lang="less">
@import  (once,optional)  "../css/base.less";


.chat_msg_detail_parent{
  border: solid 1px #f3f3f6;display: flex;flex-direction: row;
}
.chat_row_reverse{
  flex-direction: row-reverse;
}

  .chat_baseinfo{
    background: #f3f3f6;
    padding: 0 0.5rem 2.5rem 0.5rem;
    height: 90vh;
    overflow: scroll;
  }
  .chat_baseinfo_mobile{
    .chat_baseinfo;
    height: auto;
  }



  .table_css {
    margin-top: 20px;
    margin-bottom: 20px;
  }


  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .list_key{
    font-size: 13px;
    color: #bdbdbd;
    padding: 0rem 0.3rem 0 0;
    font-weight: 400;
  }
  .list_value{
    font-size: 13px;
    color: #757575;
    padding-right: 1rem;
    font-weight: 400;
  }

  .list_section{
    font-size: 13px;
    margin-top: 1.0rem;
    margin-bottom: 0.5rem;
    font-weight: bold;
  }

  .chat_content{
    overflow-y: auto;
    //height: 70vh;
    height: 100%;
    padding: 0.5rem;
    .chat_base{
      font-size: 13px;
      padding: 0px 0.5rem;
      margin-top: 1rem;
      img{
        min-width: 20%;
        max-width: 40%;
      }
    }
    .chat_base_right{
      .chat_base;
      text-align: right;
    }

    .chat_content_base{
      padding: 0.3rem 0.3rem;
      border-radius: 2px;
      float: left;
    }
    .chat_left{
      .chat_content_base;
      background:#f3f3f6;
      max-width: 80%;
      //word-wrap: break-word !important;
      //word-break:break-all !important;
      overflow: hidden !important;
      text-align:left;
      border:1px solid #e0e0e0;
      img{
        float: left;
        max-width:200px
      }
      word-wrap: break-word;
      word-break: break-all;
      white-space: pre-wrap !important;
    }





    .chat_right{
      .chat_content_base;
      color: #666;
      max-width: 80%;
      word-wrap: break-word;
      background:#f3f3f6;
      border: 1px solid #e0e0e0;
      float: right;
      .chat_right_div{
        clear: both;
        text-align: left;
        img{
          float: right;
          max-width:200px
        }
      }
    }

    .chat_img{
      background: transparent;
    }


    .chat_desc{
      font-size: 10px;
      color: #bdbdbd;
      clear: both;
      padding: 0.2rem;
    }

    .ivu-scroll-container{
      overflow-y: auto;
    }
    .desc_content{
      color:#666
    }
    .desc_title{
      font-weight:700;
      color:#333;
    }
    a{
      color:#666;
    }
    .chat_coupon{
      border: #ffbbe3 2px dashed;
      background: #fff3fa;
      background: #fff3fa;
      /*margin-top: 1rem;*/
      /*margin-bottom: 1rem;*/
      padding-left: 0.8rem !important;
      padding-right: 0.8rem !important;
      padding-bottom: 0.3rem;
      display: -webkit-flex;
      display: flex;
      flex-direction: column;
    }
  }


  .chat_send{
    border-top: 1px solid #f1f1f1;
    display: flex;
    flex-direction: row;
    align-items: center;

    i{
      padding: 0.3rem 0.8rem;
      color: #757575;
      cursor: pointer;
      font-size: 1.2em;
    }
    textarea{
      flex-grow: 1;
      height: 1.7rem;
      border: solid 1px #f1f1f1;
      outline: none;
      width:100%;
      padding: 0.2rem 0.5rem;

    }

  }
  textarea::-webkit-input-placeholder{
    color:#bdbdbd;
  }
  textarea:-moz-placeholder {
    color: #bdbdbd;
  }


  .msg_circle{
    cursor: pointer;
    position: fixed;
    right: 1rem;
    bottom: 1rem;
    .circle{
      width: 70px;
      height: 70px;
      background: #e81e63;
      -moz-border-radius: 35px;
      -webkit-border-radius: 35px;
      border-radius: 35px;
      display: flex;
      flex-direction: row;
      align-items: center;
      box-shadow: 0 2px 6px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.24);
      transition: all 0.3s cubic-bezier(.25,.8,.25,1);
      i{
        color: white;
        font-size: 1.8rem;
      }
    }

    .msg_no{
      font-weight: 600;
      font-size: 0.8rem;
      color: white;
      background: #e81e63;
      width: 26px;
      height: 26px;
      -moz-border-radius: 13px;
      -webkit-border-radius: 13px;
      border-radius: 13px;
      display: flex;
      flex-direction: row;
      align-items: center;
      box-shadow: 0 2px 6px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.24);
      transition: all 0.3s cubic-bezier(.25,.8,.25,1);
      margin-bottom: -0.5rem;

    }

  }


  .chat_spin{
    padding-top: 1.5rem;
    text-align: center;
    img{
      width: 1rem !important;
    }

  }

  .chat_prev{
    color:#bdbdbd;
    font-size: 10px;
    text-align: center;
    margin-top: 1.7rem;
    margin-bottom: 0.7rem;
    span{
      padding: 0.2rem 0.5rem;
      border: solid 1px #e0e0e0;
      cursor: pointer;
      border-radius: 14px;
      i{
        padding-right: 0.3rem;
      }
    }
    span:hover{
      color: #757575;
    }
  }
  .chat_end{
    color:#bdbdbd;
    font-size: 12px;
    text-align: center;
    margin-top: 1.7rem;
    span{
      padding: 0.2rem 0.5rem;
      border: solid 1px #bdbdbd;
      /*cursor: pointer;*/
      border-radius: 14px;
      i{
        padding-right: 0.3rem;
      }
    }
  }

  .chat_img_dialog{
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.62);
    transition: all 0.5s cubic-bezier(.25,.8,.25,1);
    position:fixed ;
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: center;
    top: 0rem;
    img{
      min-width: 30%;
      max-width: 60%;
      max-height: 80%;
      margin: 2rem 0rem;
    }

  }

  .coupons{
    margin-top: 0.8rem;
    display: -webkit-flex; /* Safari */
    display: flex;
    // 横向
    flex-direction: row;
    //超出宽度时自动换行
    flex-wrap:wrap;

    align-items: baseline;
    padding-bottom: 0.8rem;
    border-bottom: solid #f3f3f6 0.0625rem ;

    font-size: 0.85em;

  }

  .coupon_tips{
    color:red;
  }


  .coupon_parent {
    text-align: left;
    .coupon_item {
      cursor: pointer;
    }

    .coupon_item_expired {
      cursor: auto;
    }
    .coupon_title{
      color: @tiyWarningColor;
      font-size: 1rem;
      font-weight: 500;
      font-family: "LibreBaskerville-Regular";
      padding-top: 0.8rem;
    }
    .coupon_desc{
      font-size: 11px;
      margin-top: 0.3rem;
      margin-bottom: 0.3rem;
      color:#757575
    }
    .coupon_desc_warning{
      color: @tiyWarningColor;
    }

  }
  @keyframes rotation {
    from {transform: rotate(0deg);
    }to {
       transform: rotate(360deg);
     }}

  .Rotation {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    animation: rotation 2s linear infinite;
    -moz-animation: rotation  2s linear infinite;
    -webkit-animation: rotation  2s linear infinite;
    -o-animation: rotation  2s linear infinite;
  }
  .extended_list{
    display: flex;
    flex-direction: row;
    float:left;
    text-align:left;
    margin-left:10px;
    margin-top: 8px;

    div{
      padding:0 2px;
    }
    i{
      color:#666
    }
    a{
      padding: 0.3rem 0.5rem;
    }
    button{
      margin-right: 1rem;
      font-size: 12px;
    }
  }

  .message_input{
    border: none !important;
    flex-grow: 1;
    height: 4rem !important;
    border: none !important;
    outline: none;
    width:100%;
    padding: 0.2rem 0.5rem;
    resize:none
  }
  .message_text{
    color:#888;
    textarea{
      color:#888;
      width:100%;
    }
    button{
      color:  #dadada;
      outline:none;
      background-color: rgb(255, 255, 255);
      float:right;
      border-color: #dadada;
      border-radius: 15px;
      margin:0 8px 8px 10px;

    }

  }
  .chat_text{
    background-color: #42a5f5 !important;
    color:#fff !important;
  }
  .loading{
    transform: rotate(360deg);
    animation: 0.5s linear 0s infinite normal none running rotation !important;
  }
  .messageNotice{
    cursor: pointer;
    position: absolute;
    right: 20px;
    bottom: 170px;

    button{
      box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
      color: #e007e3;
      width: 110px;
      padding: .4rem .3rem;
      font-size: 12px;
      font-weight: 500;
      //  border: none;
      border: 1px solid #e007e3;
      border-radius: 20px;
      // box-shadow: 2px -1px 6px 3px #909090;
      background-color: #ffffff;
      cursor: pointer;
    }

  }
  .content_message{
    word-wrap: break-word;
    word-break: break-all;
    white-space: pre-wrap !important;
  }
  .send_footer{
    display: flex;
    align-content: flex-end;
    flex-direction: row-reverse;
    justify-content: end;
    align-items: center;
    padding: 3px;
  }

.list-item {
  .flex-colum-wrap;
  justify-items: left;
  align-items: start;

  .item-top {
    width: 100%;
    margin-bottom: 5px;
  }

  .item-content {
    width: 100%;
    margin-bottom: 10px;
    text-align: left;
  }
}
</style>
